import {
  type EbmList,
  type EbmParams,
  getEbmListApi,
  type EbmUpdateParams,
  updateEbmApi,
  type MyDialog,
  type Ebm,
  VIBRATE,
  NETWORK_TYPE
} from "@/api/ebm";
import { onMounted, reactive, ref, toRaw } from "vue";
import {
  getRtcmGroupApi,
  type RtcmGroupDTO,
  type RtcmGroupList
} from "@/api/rtcmGroup";
import { ElMessage } from "element-plus";
import { getFirmwareListApi } from "@/api/firmware";
import type { PaginationProps } from "@pureadmin/table";

export const useEbmHooks = () => {
  /** 查询表单参数 */
  const getEbmForm = ref<EbmParams>({
    pageNum: 1,
    pageSize: 10,
    remark: undefined,
    sn: undefined,
    groupId: undefined
  });
  /** 电子界桩列表 */
  const ebmList = ref<EbmList>([]);

  /** 加载中 */
  const loading = ref(false);
  /**分页*/
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  /** 获取EBM列表 */
  const getEbmList = async () => {
    loading.value = true;
    getEbmForm.value.pageSize = pagination.pageSize;
    getEbmForm.value.pageNum = pagination.currentPage;
    const res = await getEbmListApi(getEbmForm.value).finally(
      () => (loading.value = false)
    );
    ebmList.value = res.data.list;
    pagination.total = res.data.total;
  };

  /** 重置 */
  const reset = async () => {
    await getEbmList();
  };

  /** 获取分组 */
  const rtcmGroupList = ref<RtcmGroupList>([]);

  /** 获取分组 */
  const getRtcmGroup = async () => {
    const res = await getRtcmGroupApi({
      pageSize: 10000,
      pageNum: 1
    });
    if (res.code == 200) {
      console.log(res);
      rtcmGroupList.value = res.data.list;
      console.log(res, "分组列表");
    }
  };

  /**
   *  修改Dialog
   */
  const updateDialog = reactive<MyDialog<EbmUpdateParams>>({
    title: "配置修改",
    visible: false,
    form: {
      id: undefined,
      version: undefined,
      tcp1Ip: undefined,
      tcp1Port: undefined,
      tcp2Enable: undefined,
      tcp2Protocol: undefined,
      tcp2Ip: undefined,
      tcp2Port: undefined,
      tcp3Enable: undefined,
      tcp3Protocol: undefined,
      tcp3Ip: undefined,
      tcp3Port: undefined,
      sampleInv: undefined,
      uploadInv: undefined,
      shockThreshold: undefined,
      remark: undefined,
      groupId: undefined
    }
  });

  /** 打开Dialog给表单复制 */
  const openUpdateDialog = (row: Ebm) => {
    row = toRaw(row);
    const keys = Object.keys(toRaw(updateDialog.form));
    keys.forEach((key: string) => {
      updateDialog.form[key] = row[key];
    });
    updateDialog.visible = true;
    console.log(updateDialog.form);
  };

  /** 修改电子界桩配置 */
  const updateEbm = async () => {
    const res = await updateEbmApi(updateDialog.form);
    if (res.code == 200) {
      ElMessage.success("修改成功");
      updateDialog.visible = false;
      await getEbmList();
    } else {
      ElMessage.error(res.msg);
    }
  };

  /** 固件列表 */
  const firmwareList = ref<any>([]);

  /** 获取固件列表 */
  async function getFirmwareList() {
    // @ts-ignore
    const { data } = await getFirmwareListApi({
      pageNum: 1,
      pageSize: 10000
    });
    firmwareList.value = data.list ? data.list : [];
    console.log(firmwareList.value);
  }

  /** 表格列 */
  const columns: TableColumnList = [
    {
      type: "index",
      minWidth: 50,
      label: "序号",
      align: "center"
    },
    {
      prop: "deviceSn",
      label: "设备编号",
      align: "center",
      minWidth: 180
    },
    {
      prop: "version",
      label: "版本号",
      align: "center",
      minWidth: 180
    },
    {
      prop: "uploadDataTime",
      label: "最新数据时间",
      align: "center",
      minWidth: 180,
      formatter: (row: Ebm) => {
        if (!row.uploadDataTime) {
          return <el-tag>暂无</el-tag>;
        }
        return new Date(row.uploadDataTime * 1000).toLocaleString();
      }
    },
    {
      prop: "lon",
      label: "经度",
      align: "center",
      minWidth: 180
    },
    {
      prop: "lat",
      label: "纬度",
      align: "center",
      minWidth: 180
    },
    {
      prop: "temp",
      label: "温度",
      align: "center",
      minWidth: 180
    },
    {
      prop: "humidity",
      label: "湿度",
      align: "center",
      minWidth: 180
    },
    {
      prop: "zd",
      label: "振动状态",
      align: "center",
      minWidth: 180,
      formatter: (row: Ebm) => {
        switch (row.zd) {
          case VIBRATE.THERE_IS_VIBRATION:
            return <el-tag type="warning">有振动</el-tag>;
          case VIBRATE.NO_VIBRATION:
            return <el-tag type="success">无振动</el-tag>;
          default:
            return <el-tag type="info">未知状态</el-tag>;
        }
      }
    },
    {
      prop: "angle",
      label: "z轴角度",
      align: "center",
      minWidth: 180
    },
    {
      prop: "volt",
      label: "电压",
      align: "center",
      minWidth: 180
    },
    {
      prop: "type",
      label: "报文类型",
      align: "center",
      minWidth: 180,
      formatter: (row: Ebm) => {
        switch (row.type) {
          case NETWORK_TYPE.TIMING:
            return <el-tag type="success">定时</el-tag>;
          case NETWORK_TYPE.WARNING:
            return <el-tag type="warning">报警</el-tag>;
          default:
            return <el-tag type="info">未知类型</el-tag>;
        }
      }
    },
    {
      prop: "groupId",
      label: "分组名称",
      align: "center",
      minWidth: 180,
      formatter: (row: Ebm) => {
        console.log("rtcmGroupList", rtcmGroupList.value);
        // 修改后
        const group = rtcmGroupList.value?.find(
          (item: RtcmGroupDTO) => item.id == row.groupId
        );
        return group?.groupName ?? "暂无分组";
      }
    },
    {
      prop: "createdAt",
      label: "注册时间",
      align: "center",
      minWidth: 180,
      formatter: (row: Ebm) => {
        if (!row.createdAt) return <el-tag>暂无</el-tag>;
        const dateStr = row.createdAt.split("T")[0];
        const timeStr = row.createdAt.split("T")[1].split(".")[0];
        return dateStr + " " + timeStr;
      },
      fixed: "right"
    },
    {
      prop: "remark",
      label: "备注",
      align: "center",
      minWidth: 180,
      fixed: "right",
      formatter: (row: Ebm) => {
        return (
          <div>
            {row.remark.length > 10
              ? row.remark.substring(0, 10) + "..."
              : row.remark}{" "}
          </div>
        );
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 300,
      slot: "operation"
    }
  ];

  onMounted(async () => {
    await getRtcmGroup();
    await getEbmList();
    await getFirmwareList();
  });

  return {
    columns,
    ebmList,
    loading,
    reset,
    getEbmForm,
    getEbmList,
    rtcmGroupList,
    updateDialog,
    updateEbm,
    firmwareList,
    openUpdateDialog,
    pagination
  };
};
